package com.declum.archon.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class CreateChunkRequest extends BaseRequest {

	public void createChunk(String name, String key, String proxyFor,
			String chunkid, String forwardTo[]) throws IOException {
		DataOutputStream out = new DataOutputStream(this.socket
				.getOutputStream());
		out.write(RequestType.CREATE_CHUNK.getBytes());
		DataInputStream in = new DataInputStream(this.socket.getInputStream());

		byte[] data = new byte[1024];
		int totalCount = 0;

		if (!this.waitForAck(in)) {

		}

		String header = this.getHeaderSring("name", name);
		header += this.getHeaderSring("key", key);
		if (proxyFor != null) {
			header += this.getHeaderSring("proxyfor", proxyFor);
		}
		header += this.getHeaderSring("chunkid", chunkid);
		if (forwardTo.length > 0) {
			header += this.getHeaderSring("forwardTo", forwardTo);
		}
		header += "\r\n";
		System.out.println(header);
		out.write(header.getBytes());
		if (!this.waitForAck(in)) {
			totalCount = in.read(data);
			throw new CreateChunkException(new String(data, 0, totalCount));
		}
	}

	private boolean waitForAck(DataInputStream in) throws IOException {
		byte[] data = new byte[4];
		int count = 0;
		int totalCount = 0;
		while (true) {
			count = in.read(data, count, 3 - count);
			if ((count == -1) || (totalCount == 3)) {
				break;
			}
			totalCount += count;
		}
		return (new String(data, 0, totalCount).equals("ACK"));
	}

	public static void main(String[] args) throws IOException {
		CreateChunkRequest request = (CreateChunkRequest) RequestFactory
				.getInstance().getRequestInstance(RequestType.CREATE_CHUNK);
		request.connect("localhost", 12347);
		request.createChunk("Master", "1004356", null, "1090", new String[] {
				"localhost:12348", "localhost:12349" });
	}
}
